package com.zyg.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyg.common.entity.PayVo;
import com.zyg.common.entity.TbPayLog;
import com.zyg.common.utils.IdWorker;
import com.zyg.order.dao.TbOrderItemMapper;
import com.zyg.order.dao.TbPayLogMapper;
import com.zyg.order.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.order.dao.TbOrderMapper;
import com.zyg.order.service.TbOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by WF on 2021/11/12 14:25
 */
@Service

public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder> implements TbOrderService{
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TbOrderItemMapper itemMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbPayLogMapper payLogMapper;
    //1. 根据登录名得到购物车列表
    @Override
    public List<Cart> findCartList(String name) {
        String s = redisTemplate.opsForValue().get(name);
        return JSON.parseArray(s,Cart.class);
    }

    //2. 保存订单
    @Override
    @Transactional
    public void save(String name, TbOrder tbOrder) {
        //2.1 从redis中取出购物车数据
        List<Cart> cartList = findCartList(name);
        double total = 0;       //所有订单的所金额
        String ids = "";        //代表订单编号字符串
        //2.2 遍历购物车添加订单
        for (Cart cart : cartList) {
            //2.2.1 定义要添加的订单
            TbOrder order = new TbOrder();
            //2.2.2 设置要添加的订单数据
            //① 生成订单id
            long orderId = idWorker.nextId();
            ids += orderId + ",";
            order.setOrderId(orderId);
            order.setCreateTime(new Date());
            order.setPaymentType(tbOrder.getPaymentType());
            order.setSellerId(cart.getSellerId());
            order.setStatus("1");           //状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭,7、待评价
            order.setReceiver(tbOrder.getReceiver());
            order.setReceiverAreaName(tbOrder.getReceiverAreaName());
            order.setReceiverMobile(tbOrder.getReceiverMobile());
            order.setUpdateTime(new Date());
            order.setSourceType("2");  //订单来源：1:app端，2：pc端，3：M端，4：微信端，5：手机qq端
            order.setUserId(name);

            //2.2.3 定义代表此订单的总金额
            double sum = 0;
            //2.2.4 遍历订单项
            for (TbOrderItem item : cart.getOrderItemList()) {
                //① 为订单项设置值
                item.setOrderId(orderId);       //设置订单项的外键
                item.setSellerId(cart.getSellerId());
                //② 设置订单项的id
                long id = idWorker.nextId();
                item.setId(id);
                //③ 计算小计金额
                item.setTotalFee(new BigDecimal(item.getPrice().doubleValue() * item.getNum()));
                //④ 累加sum
                sum += item.getTotalFee().doubleValue();
                //⑤ 添加订单项
                itemMapper.insert(item);
            }

            //2.2.5 为订单设置总金额
            order.setPayment(new BigDecimal(sum));
            //2.2.6 添加订单
            orderMapper.insert(order);
            total += sum;
        }

        //2.2.7 保存支付日志
        if(tbOrder.getPaymentType().equals("1")){  //在线支付
            //① 定义支付日志对象，准备添加
            TbPayLog payLog = new TbPayLog();
            //② 为字段赋值
            long id = idWorker.nextId();
            payLog.setCreateTime(new Date());
            payLog.setOutTradeNo(id+"");
            payLog.setPayType("2");
            payLog.setTotalFee((long)(total * 100));
            payLog.setTradeState("0");      //0：未支付 1：代表己支付
            payLog.setUserId(name);
            ids = ids.substring(0,ids.length()-1);
            payLog.setOrderList(ids);
            //③ 添加到数据库
            payLogMapper.insert(payLog);
            //④ 保存订单日志到redis中
            redisTemplate.opsForValue().set(name + ":paylog",JSON.toJSONString(payLog),10, TimeUnit.DAYS);
        }

        //2.2.8 清空redis

    }

    //3. 从redis中得到支付日志
    @Override
    public TbPayLog getPayLogFromRedis(String name) {
        return JSON.parseObject(redisTemplate.opsForValue().get(name+":paylog"),TbPayLog.class);
    }

    //4. 根据登录名得到支付日志并生成下单请求参数payVo对象
    @Override
    public PayVo findPayVoByname(String name, String outTradeNo) {
        //4.1 得到支付日志
        String s = redisTemplate.opsForValue().get(name + ":paylog");
        TbPayLog payLog = JSON.parseObject(s, TbPayLog.class);
        //4.2 构造下单请求参数
        PayVo vo  = new PayVo();
        vo.setOut_trade_no(payLog.getOutTradeNo());
        vo.setTotal_amount(payLog.getTotalFee() + "");
        vo.setSubject("泽易购商城支付订单");
        vo.setBody("一个良好的网上交易平台...");
        return vo;
    }

    //5. 根据登录名得到此用户的订单列表
    @Override
    public List<TbOrder> findOrderListByname(String name) {
        List<TbOrder> orderList = this.list(new QueryWrapper<TbOrder>().eq("user_id", name));
        for (TbOrder tbOrder : orderList) {
            Long orderId = tbOrder.getOrderId();
            List<TbOrderItem> orderItems = itemMapper.selectList(new QueryWrapper<TbOrderItem>().eq("order_id", orderId));
            tbOrder.setOrderItemEntities(orderItems);
        }
        return orderList;
    }

    //6. 根据支付日志订单编号查询支付日志
    @Override
    public TbPayLog findPayLog(String id) {
        return payLogMapper.selectById(id);
    }
}
